import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'base_service.dart';

/// 报警消息服务类 - GetX服务
class AlarmService extends GetxService {
  final BaseService _baseService = BaseService();

  /// 获取所有告警类型
  Future<Map<String, dynamic>> getAlarmTypes() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/alarm/getAlarmTypes',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取告警类型失败');
        }
      } else {
        throw Exception('获取告警类型响应数据为空');
      }
    } on DioException catch (e) {
      print('获取告警类型网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取告警类型错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取未读消息数
  Future<Map<String, dynamic>> getUnreadAlarmCount({
    String? deviceId,
    String? startAt,
    String? endAt,
  }) async {
    try {
      String url = '/alarm/unreadAlarmCnt';

      // 构建查询参数
      List<String> queryParams = [];
      if (deviceId != null && deviceId.isNotEmpty) {
        queryParams.add('deviceId=$deviceId');
      }
      if (startAt != null && startAt.isNotEmpty) {
        queryParams.add('startAt=${Uri.encodeComponent(startAt)}');
      }
      if (endAt != null && endAt.isNotEmpty) {
        queryParams.add('endAt=${Uri.encodeComponent(endAt)}');
      }

      if (queryParams.isNotEmpty) {
        url += '?${queryParams.join('&')}';
      }

      print('📊 获取未读消息数请求URL: $url');

      final response = await _baseService.get<Map<String, dynamic>>(url);

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取未读消息数失败');
        }
      } else {
        throw Exception('获取未读消息数响应数据为空');
      }
    } on DioException catch (e) {
      print('获取未读消息数网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取未读消息数错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取报警消息列表（分页）
  Future<Map<String, dynamic>> getAlarmMessages({
    List<String>? hsIds,
    List<int>? alarmTypes,
    String? startTime,
    String? endTime,
    int pageNo = 1,
    int pageSize = 10,
    int? videoType,
    int? readStatus,
    String? deviceId,
  }) async {
    try {
      final requestData = <String, dynamic>{
        'pageNo': pageNo,
        'pageSize': pageSize,
      };

      if (hsIds != null && hsIds.isNotEmpty) {
        requestData['hsIds'] = hsIds;
      }
      if (alarmTypes != null && alarmTypes.isNotEmpty) {
        requestData['alarmTypes'] = alarmTypes;
      }
      if (startTime != null) {
        requestData['startTime'] = startTime;
      }
      if (endTime != null) {
        requestData['endTime'] = endTime;
      }
      if (videoType != null) {
        requestData['videoType'] = videoType;
      }
      if (readStatus != null) {
        requestData['readStatus'] = readStatus;
      }
      if (deviceId != null && deviceId.isNotEmpty) {
        requestData['deviceId'] = deviceId;
      }

      final response = await _baseService.post<Map<String, dynamic>>(
        '/alarm/pageMessage',
        data: requestData,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取报警消息列表失败');
        }
      } else {
        throw Exception('获取报警消息列表响应数据为空');
      }
    } on DioException catch (e) {
      print('获取报警消息列表网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取报警消息列表错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 标记消息已读
  Future<Map<String, dynamic>> markAlarmMessageRead({
    String? msgId,
    String? hsId,
    String? deviceId,
    String? readDay,
  }) async {
    try {
      final requestData = <String, dynamic>{};

      // 当参数为空时为一键已读所有消息
      if (msgId != null) {
        requestData['msgId'] = msgId;
      }
      if (hsId != null) {
        requestData['hsId'] = hsId;
      }
      if (deviceId != null && deviceId.isNotEmpty) {
        requestData['deviceId'] = deviceId;
      }
      if (readDay != null && readDay.isNotEmpty) {
        requestData['readDay'] = readDay;
      }

      final response = await _baseService.post<Map<String, dynamic>>(
        '/alarm/readAlarmMsg',
        data: requestData,
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '标记消息已读失败');
        }
      } else {
        throw Exception('标记消息已读响应数据为空');
      }
    } on DioException catch (e) {
      print('标记消息已读网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('标记消息已读错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 一键已读所有消息
  Future<Map<String, dynamic>> markAllMessagesRead({
    String? readDay,
    String? deviceId,
  }) async {
    try {
      final requestData = <String, dynamic>{};
      if (readDay != null && readDay.isNotEmpty) {
        requestData['readDay'] = readDay;
      }
      if (deviceId != null && deviceId.isNotEmpty) {
        requestData['deviceId'] = deviceId;
      }

      final response = await _baseService.post<Map<String, dynamic>>(
        '/alarm/readAlarmMsg',
        data: requestData, // 空参数表示一键已读所有，有readDay表示已读某天所有，有deviceId表示只标记该设备的消息
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '一键已读失败');
        }
      } else {
        throw Exception('一键已读响应数据为空');
      }
    } on DioException catch (e) {
      print('一键已读网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('一键已读错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }

  /// 获取按通道分组的报警消息
  Future<Map<String, dynamic>> getChannelAlarmMessages() async {
    try {
      final response = await _baseService.get<Map<String, dynamic>>(
        '/alarm/getChannelMsg',
      );

      if (response.data != null) {
        final data = response.data!;
        if (data['code'] == 0 && data['success'] == true) {
          return data;
        } else {
          throw Exception(data['msg'] ?? '获取通道报警消息失败');
        }
      } else {
        throw Exception('获取通道报警消息响应数据为空');
      }
    } on DioException catch (e) {
      print('获取通道报警消息网络错误: ${e.message}');
      throw Exception('网络环境不佳，请稍后尝试');
    } catch (e) {
      print('获取通道报警消息错误: $e');
      throw Exception('网络环境不佳，请稍后尝试');
    }
  }
}
